package com.monitor.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.monitor.commons.HttpTookit;
import com.monitor.commons.StringUtil;
import com.monitor.config.yunke.YunKeConfig;
import com.monitor.config.yunke.YunKeUtil;
import com.monitor.dao.IWechatDao;
import com.monitor.modelExt.WechatExt;
import com.monitor.pubInter.AbstractBaseService;
import com.monitor.pubInter.IBaseDao;
import com.monitor.pubInter.exception.SkException;
import com.monitor.searchExt.WechatSearchExt;
import com.monitor.service.IWechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;


/**
 * @author afeng
 * @Date 2025-03-17 10:50:14
 * @description WechatService      微信好友/群
 */
@Service(value = "wechatService")
@Slf4j
public class WechatServiceImpl extends AbstractBaseService<WechatExt, WechatSearchExt, String> implements IWechatService {

    @Resource(name = "wechatDao")
    private IWechatDao wechatDao;

    @Autowired
    private YunKeUtil yunKeUtil;
    @Autowired
    private YunKeConfig yunKeConfig;

    @Override
    public IBaseDao<WechatExt, WechatSearchExt, String> getDao() {
        return wechatDao;
    }

    @Override
    public void syncWechatData() throws SkException {
        Long creatTime = 1420041600000l; // 默认时间
//        如果有数据,根据addTime来获取
        WechatSearchExt searchExt = WechatSearchExt.getInstance();
        searchExt.setOrderBy(WechatExt.CREATE_TIME);
        searchExt.setOrderDesc("desc");
        searchExt.setLimit(1);
        WechatExt wechatExt = getDetailBySearch(searchExt);
        if (StringUtil.isNotObjEmpty(wechatExt)) {
            creatTime = wechatExt.getCreateTime().getTime();
        }
        wechatData(creatTime);
    }

    private void wechatData(Long createTimestamp) {
        try {

            //定义请求路径
            String url = yunKeConfig.getUrl() + "open/wechat/getAllFriends";
            //组装请求头
            long timestamp = new Date().getTime();
            Map<String, String> headsMap = yunKeUtil.getHeadMap(timestamp);
            //组装请求参数
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("type", 1);
            paramsMap.put("timestamp", createTimestamp);
            String res = HttpTookit.doPostHeader(url, paramsMap, headsMap);
            log.info("获取的微信账号:" + res);
            JSONObject resObject = JSONObject.parseObject(res);
            AtomicReference<Long> nextTime = new AtomicReference<>(0l);
            if (resObject.getBoolean("success")) {
                JSONArray dataArr = resObject.getJSONArray("data");
                if (StringUtil.isNotObjEmpty(dataArr) && !dataArr.isEmpty()) {
//                    如果有一条数据,查看是否也已经存在库中
                    WechatSearchExt searchExt = WechatSearchExt.getInstance();
                    JSONObject dataObj = dataArr.getJSONObject(0);
                    searchExt.setYkIdLike(dataObj.getString("id"));
                    WechatExt wechatExt = getDetailBySearch(searchExt);
                    if (StringUtil.isNotObjEmpty(wechatExt)) {
//                        有村就结束
                        return;
                    }
                }

                dataArr.forEach((data) -> {
                    JSONObject item = JSONObject.from(data);
                    WechatExt wechatExt = JSONObject.parseObject(JSONObject.toJSONString(data), WechatExt.class);
                    wechatExt.setId(null);
                    wechatExt.setYkId(item.getString("id"));
                    nextTime.set(wechatExt.getCreateTime().getTime());
                    try {
                        wechatDao.insert(wechatExt);
                    } catch (SkException e) {
                        throw new RuntimeException(e);
                    }
                });


                log.info("共有数据:" + dataArr.size() + "条");
                if (StringUtil.isNotObjEmpty(dataArr) && dataArr.size() > 1) {
                    Thread.sleep(5000);
                    wechatData(nextTime.get());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}